package org.taofuxn.framework.ui.activity;

import android.graphics.Bitmap;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.taofuxn.yycreazy.R;


import org.taofuxn.framework.ui.base.ToobarActivity;
import org.taofuxn.framework.ui.view.FgWebChromeClient;

import butterknife.InjectView;

/**
 */
public class WebActivity extends ToobarActivity {

    @InjectView(R.id.webProgressBar)
    ProgressBar progressBar;
    @InjectView(R.id.webView)
    WebView mWebView;
    private String urlHttp;
    private FgWebChromeClient mfgcclient;
    private MyWebViewClient myWebViewClient;

    @Override
    protected int setContentLayout() {
        return R.layout.activity_webview;
    }

    @Override
    protected void init() {
        urlHttp = getIntent().getStringExtra("url");
        initWebView();
    }


    private void initWebView() {
        myWebViewClient = new MyWebViewClient();
        mfgcclient = new FgWebChromeClient(WebActivity.this, progressBar);
        mWebView.requestFocusFromTouch();
        WebSettings mSettings = mWebView.getSettings();
        mSettings.setJavaScriptEnabled(true);
        mSettings.setBuiltInZoomControls(true);
        mSettings.setSupportZoom(true);
        mSettings.setUseWideViewPort(true);//设置此属性，可任意比例缩放
        mSettings.setLoadWithOverviewMode(true);
        mSettings.setAllowFileAccess(true);
        mSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        mSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//缓存优先
        mWebView.loadUrl(urlHttp);
        mWebView.setWebViewClient(myWebViewClient);
        mWebView.setWebChromeClient(mfgcclient);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mWebView.setVisibility(View.GONE);
    }

    class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            urlHttp = url;
            return true;
        }

        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);
            if (progressBar != null) {
                progressBar.setVisibility(View.GONE);
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (null != progressBar)
                progressBar.setVisibility(View.VISIBLE);
        }

    }
}
